using System.Collections;
using System.Collections.Generic;
using Spine.Unity;
using TreeEditor;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class SpineTouchUnit : MonoBehaviour
{
    public void Init(SpineTouchConfig touchConfig, SkeletonUtilityBone utilityBone, DynamicObject dynamicObject, UnityAction clickAction)
    {
        //添加Follower
        var follower = gameObject.AddComponent<BoneFollowerGraphic>();
        follower.boneName = touchConfig.skeleton;
        follower.skeletonGraphic = utilityBone.hierarchy.skeletonGraphic;

        //添加交互控件
        var touchObj = new GameObject("TouchButton");
        touchObj.transform.SetParent(transform, false);
        touchObj.transform.localPosition = Vector3.zero;
        touchObj.transform.localRotation = Quaternion.identity;
        touchObj.transform.localScale = Vector3.one;

        //添加按钮
        RectTransform rect = null;
        if (!touchObj.TryGetComponent(out rect))
        {
            rect = touchObj.AddComponent<RectTransform>();
        }

        switch (touchConfig.touchType)
        {
            case SpineTouchType.Collider:
                CreateCollider(touchConfig,utilityBone,rect,clickAction);
                break;
            default:
                CreateButton(touchConfig, rect, clickAction);
                break;
        }
    }

    private void CreateCollider(SpineTouchConfig touchConfig, SkeletonUtilityBone utilityBone, RectTransform rect, UnityAction clickAction)
    {
        //var col = rect.gameObject.AddComponent<PolygonCollider2D>();
        //找到骨骼附带的碰撞体
        var attachCol = utilityBone.transform.Find($"[BoundingBox]{touchConfig.boundingBoxName}").GetComponent<PolygonCollider2D>();
        var eventHandler = attachCol.gameObject.AddComponent<TouchEventHandler>();
        attachCol.gameObject.AddComponent<RectTransform>().localScale *= 100;
        eventHandler.ClickEvent = clickAction;
    }

    private void CreateButton(SpineTouchConfig touchConfig, RectTransform rect, UnityAction clickAction)
    {
        var img = rect.gameObject.AddComponent<Image>();
        var eventHandler = rect.gameObject.AddComponent<TouchEventHandler>();
        eventHandler.ClickEvent = clickAction;
        img.color = new Color(1, 1, 1, 0.3f);
        if (touchConfig.size != Vector2.zero)
        {
            rect.localScale = new Vector3(touchConfig.size.x, touchConfig.size.y, 1);
        }

        rect.eulerAngles = touchConfig.eulerAngles;
    }
}